package com.laundry.config;

import com.laundry.entity.*;
import com.laundry.repository.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalTime;

@Component
@Profile({"dev", "prod"})
@RequiredArgsConstructor
@Slf4j
public class ProductionDataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final MerchantRepository merchantRepository;
    private final ServiceCategoryRepository serviceCategoryRepository;
    private final ServiceRepository serviceRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void run(String... args) throws Exception {
        log.info("开始初始化生产环境数据...");
        
        // 检查是否已经初始化过
        if (userRepository.count() > 0) {
            log.info("数据已存在，跳过初始化");
            return;
        }

        initializeProductionData();
        log.info("生产环境数据初始化完成");
    }

    private void initializeProductionData() {
        // 1. 创建管理员用户
        createAdminUser();
        
        // 2. 创建服务分类
        createServiceCategories();
        
        // 3. 创建商家用户和商家信息
        createMerchantsAndUsers();
        
        // 4. 创建服务项目
        createServices();
        
        // 5. 创建测试用户
        createTestUser();
    }

    private void createAdminUser() {
        // 检查管理员是否已存在
        if (userRepository.findByUsername("admin").isPresent()) {
            log.info("管理员用户已存在，跳过创建");
            return;
        }
        
        User admin = new User();
        admin.setUsername("admin");
        admin.setEmail("admin@laundrycare.com");
        admin.setPassword(passwordEncoder.encode("admin123"));
        admin.setMobile("13800000000");
        admin.setNickname("系统管理员");
        admin.setStatus(User.UserStatus.ACTIVE);
        admin.setRole(User.UserRole.ADMIN);
        admin.setEmailVerified(true);
        admin.setMobileVerified(true);
        admin.setRealNameVerified(true);
        userRepository.save(admin);
        log.info("创建管理员用户: {}", admin.getUsername());
    }

    private void createServiceCategories() {
        // 检查是否已有服务分类
        if (serviceCategoryRepository.count() > 0) {
            log.info("服务分类已存在，跳过创建");
            return;
        }
        
        String[][] categories = {
            {"普通洗涤", "日常衣物清洗服务", "wash"},
            {"干洗服务", "高档衣物干洗护理", "dry-clean"},
            {"熨烫整理", "专业熨烫和整理服务", "iron"},
            {"特殊护理", "皮具、丝绸等特殊材质护理", "special"},
            {"家居清洗", "床品、窗帘等家居用品清洗", "home"},
            {"鞋靴护理", "各类鞋靴清洗和保养", "shoes"}
        };

        for (int i = 0; i < categories.length; i++) {
            ServiceCategory category = new ServiceCategory();
            category.setName(categories[i][0]);
            category.setDescription(categories[i][1]);
            category.setIcon(categories[i][2]);
            category.setSortOrder(i + 1);
            category.setStatus(ServiceCategory.CategoryStatus.ACTIVE);
            serviceCategoryRepository.save(category);
        }
        log.info("创建了 {} 个服务分类", categories.length);
    }

    private void createMerchantsAndUsers() {
        String[][] merchantData = {
            {"merchant001", "contact@cleanmaster.com", "洁净大师", "洁净大师洗衣连锁", 
             "专业洗衣服务20年，采用进口设备和环保洗涤剂，为您提供优质的洗衣体验", 
             "北京市朝阳区建国路88号", "400-001-1001", "07:00", "23:00", "4.8", "1256", "5680", "8.00", "30.00", "13900001001"},
            {"merchant002", "service@premiumcare.com", "优护洗衣", "优护精品洗衣", 
             "高端洗衣护理专家，专注奢侈品和精品服装的专业护理，让每一件衣物焕然一新", 
             "上海市浦东新区陆家嘴环路100号", "400-001-1002", "08:00", "22:00", "4.9", "892", "3240", "12.00", "50.00", "13900001002"},
            {"merchant003", "info@quickwash.com", "快洗专家", "快洗专家24小时", 
             "24小时营业的快速洗衣服务，急件2小时取，普通件当日达，便民服务第一", 
             "广州市天河区珠江新城CBD核心区", "400-001-1003", "00:00", "23:59", "4.6", "2108", "8960", "6.00", "20.00", "13900001003"},
            {"merchant004", "hello@luxurycare.com", "奢护洗衣", "奢护国际洗衣", 
             "国际标准的奢侈品护理服务，拥有LV、Hermès等品牌官方认证，呵护您的每一件珍品", 
             "深圳市南山区深南大道9999号", "400-001-1004", "09:00", "21:00", "4.9", "567", "1890", "15.00", "100.00", "13900001004"},
            {"merchant005", "support@ecogreen.com", "绿色环保", "绿色环保洗衣", 
             "100%环保洗涤，无磷无害，保护环境从洗衣开始，健康洗衣新选择", 
             "成都市锦江区春熙路168号", "400-001-1005", "08:30", "21:30", "4.7", "1034", "4520", "5.00", "25.00", "13900001005"}
        };

        for (String[] data : merchantData) {
            // 检查用户是否已存在
            if (userRepository.findByUsername(data[0]).isPresent()) {
                log.info("商家用户 {} 已存在，跳过创建", data[0]);
                continue;
            }
            
            // 创建商家用户
            User merchantUser = new User();
            merchantUser.setUsername(data[0]);
            merchantUser.setEmail(data[1]);
            merchantUser.setPassword(passwordEncoder.encode("merchant123"));
            merchantUser.setMobile(data[14]); // 使用不同的手机号
            merchantUser.setNickname(data[2]);
            merchantUser.setStatus(User.UserStatus.ACTIVE);
            merchantUser.setRole(User.UserRole.MERCHANT);
            merchantUser.setEmailVerified(true);
            merchantUser.setMobileVerified(true);
            merchantUser.setRealNameVerified(true);
            User savedUser = userRepository.save(merchantUser);

            // 创建商家信息
            Merchant merchant = new Merchant();
            merchant.setUser(savedUser);
            merchant.setShopName(data[3]);
            merchant.setName(data[3]);
            merchant.setDescription(data[4]);
            merchant.setAddress(data[5]);
            merchant.setPhone(data[6]);
            merchant.setEmail(data[1]);
            merchant.setStatus(Merchant.MerchantStatus.ACTIVE);
            merchant.setOpenTime(LocalTime.parse(data[7]));
            merchant.setCloseTime(LocalTime.parse(data[8]));
            merchant.setIsOpen(true);
            merchant.setRating(new BigDecimal(data[9]));
            merchant.setReviewCount(Integer.parseInt(data[10]));
            merchant.setOrderCount(Integer.parseInt(data[11]));
            merchant.setDeliveryFee(new BigDecimal(data[12]));
            merchant.setMinOrderAmount(new BigDecimal(data[13]));
            merchantRepository.save(merchant);
        }
        log.info("创建了商家用户和商家信息");
    }

    private void createServices() {
        // 获取所有商家和分类
        var merchants = merchantRepository.findAll();
        var categories = serviceCategoryRepository.findAll();
        
        if (merchants.isEmpty() || categories.isEmpty()) {
            log.warn("商家或分类数据为空，跳过服务创建");
            return;
        }

        // 为每个商家创建服务
        for (int i = 0; i < merchants.size(); i++) {
            Merchant merchant = merchants.get(i);
            createServicesForMerchant(merchant, categories, i);
        }
        log.info("为所有商家创建了服务项目");
    }

    private void createServicesForMerchant(Merchant merchant, java.util.List<ServiceCategory> categories, int merchantIndex) {
        String[][][] serviceData = {
            // 商家1的服务
            {{"精品衬衫洗涤", "专业衬衫洗涤，去污除渍，熨烫整形", "15.00", "20.00", "PIECE", "24", "true", "true", "0"},
             {"休闲外套清洗", "休闲外套深度清洗，保型护色", "25.00", "30.00", "PIECE", "48", "false", "true", "0"},
             {"西装干洗套装", "高档西装专业干洗，保持版型", "45.00", "55.00", "SET", "72", "true", "true", "1"},
             {"精细熨烫服务", "专业熨烫，恢复衣物最佳状态", "8.00", "10.00", "PIECE", "2", "false", "false", "2"}},
            // 商家2的服务
            {{"奢侈品干洗护理", "国际标准奢侈品护理，品牌认证", "120.00", "150.00", "PIECE", "120", "true", "true", "1"},
             {"真丝服装护理", "真丝面料专业护理，保持光泽", "80.00", "100.00", "PIECE", "96", "true", "true", "3"},
             {"皮具护理保养", "高端皮具清洁保养，延长使用寿命", "200.00", "250.00", "PIECE", "168", "false", "true", "3"},
             {"羊绒大衣护理", "羊绒面料专业护理，防缩防变形", "90.00", "120.00", "PIECE", "96", "true", "false", "1"}},
            // 商家3的服务
            {{"快速洗涤2小时", "急件快洗服务，2小时即可取件", "20.00", "25.00", "PIECE", "2", "true", "true", "0"},
             {"标准洗涤当日达", "标准洗涤服务，当日可取", "12.00", "15.00", "PIECE", "8", "true", "true", "0"},
             {"床品四件套清洗", "床单被套枕套清洗，除螨杀菌", "35.00", "45.00", "SET", "24", "false", "true", "4"},
             {"运动服装清洗", "运动服专业清洗，去汗渍异味", "18.00", "22.00", "PIECE", "12", "false", "false", "0"}},
            // 商家4的服务
            {{"LV包包护理", "Louis Vuitton官方认证护理服务", "300.00", "400.00", "PIECE", "240", "true", "true", "1"},
             {"Hermès丝巾护理", "爱马仕丝巾专业护理，保持原色", "150.00", "200.00", "PIECE", "120", "true", "true", "3"},
             {"高定礼服护理", "高级定制礼服专业护理", "500.00", "600.00", "PIECE", "240", "false", "true", "1"},
             {"奢侈品鞋履护理", "高端鞋履清洁保养护理", "180.00", "220.00", "PIECE", "96", "false", "false", "5"}},
            // 商家5的服务
            {{"环保洗涤标准版", "100%环保洗涤剂，温和不伤衣", "10.00", "12.00", "PIECE", "24", "true", "true", "0"},
             {"有机棉服装洗涤", "有机棉面料专用环保洗涤", "16.00", "20.00", "PIECE", "36", "false", "true", "0"},
             {"婴幼儿用品清洗", "婴幼儿衣物专用无害清洗", "20.00", "25.00", "PIECE", "48", "true", "true", "4"},
             {"环保干洗服务", "环保干洗溶剂，无毒无害", "35.00", "40.00", "PIECE", "72", "false", "false", "1"}}
        };

        if (merchantIndex < serviceData.length) {
            String[][] services = serviceData[merchantIndex];
            for (String[] serviceInfo : services) {
                Service service = new Service();
                service.setMerchant(merchant);
                service.setCategory(categories.get(Integer.parseInt(serviceInfo[8])));
                service.setName(serviceInfo[0]);
                service.setDescription(serviceInfo[1]);
                service.setPrice(new BigDecimal(serviceInfo[2]));
                service.setOriginalPrice(new BigDecimal(serviceInfo[3]));
                service.setPriceUnit(Service.PriceUnit.valueOf(serviceInfo[4].toUpperCase()));
                service.setProcessingTime(Integer.parseInt(serviceInfo[5]));
                service.setIsHot(Boolean.parseBoolean(serviceInfo[6]));
                service.setIsRecommended(Boolean.parseBoolean(serviceInfo[7]));
                service.setStatus(Service.ServiceStatus.ACTIVE);
                serviceRepository.save(service);
            }
        }
    }

    private void createTestUser() {
        // 检查测试用户是否已存在
        if (userRepository.findByUsername("13900139000").isPresent()) {
            log.info("测试用户已存在，跳过创建");
            return;
        }
        
        User testUser = new User();
        testUser.setUsername("13900139000");
        testUser.setEmail("user@laundrycare.com");
        testUser.setPassword(passwordEncoder.encode("123456"));
        testUser.setMobile("13900139000");
        testUser.setNickname("测试用户");
        testUser.setStatus(User.UserStatus.ACTIVE);
        testUser.setRole(User.UserRole.USER);
        testUser.setEmailVerified(true);
        testUser.setMobileVerified(true);
        testUser.setRealNameVerified(false);
        userRepository.save(testUser);
        log.info("创建测试用户: {}", testUser.getUsername());
    }
}
